package com.gitee.wsl.lang.ubytearray.api

 interface UInput {

     fun read(): UByte

     @OptIn(ExperimentalUnsignedTypes::class)
     fun readBytes(length: Int): UByteArray

     fun readUShort(): UShort {
        return ((read().toUInt() shl 8) or read().toUInt()).toUShort()
    }

     fun readUInt(): UInt {
        var number = 0u
        for (i in 0..3) {
            number = number or (read().toUInt() shl ((3 - i) * 8))
        }
        return number
    }

     fun readULong(): ULong {
        var number: ULong = 0u
        for (i in 0..7) {
            number = number or (read().toULong() shl ((7 - i) * 8))
        }
        return number
    }
}

 fun UInput.decodeVariableByteInteger(): UInt {
    var multiplier = 1u
    var value = 0u
    do {
        val encodedByte = read().toUInt()
        value += (encodedByte and 127u) * multiplier
        if (multiplier > 128u * 128u * 128u) {
            throw Exception("Malformed Variable Byte Integer")
        }
        multiplier *= 128u
    } while ((encodedByte and 128u) != 0u)
    return value
}
